package com.touchstone.synchdata.common.exception.handler;

import com.touchstone.synchdata.common.exception.BusinessException;
import com.touchstone.synchdata.common.result.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description : 统一异常处理
 * @Author : hunter
 * @Date: 2019-07-11 17:18
 **/
@Slf4j
@ControllerAdvice
public class CommonExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public ResultVO handleException(BusinessException e) {
        String msg = e.getMessage();
        log.info("{}", msg);
        msg = msg.contains("，原因为") ? msg.substring(msg.indexOf("，原因为")) : msg;
        return ResultVO.fail(msg);
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO validationBodyException(MethodArgumentNotValidException e) {
        String message;
        FieldError fieldError = e.getBindingResult().getFieldError();
        if(fieldError != null){
            message = fieldError.getDefaultMessage();
            log.info("参数校验异常:{}({})", message, fieldError.getField());
        }else{
            message = e.getMessage();
            log.info("参数校验异常:{}", message);
        }
        return ResultVO.fail(message);
    }

    @ResponseBody
    @ExceptionHandler(HttpMessageConversionException.class)
    public ResultVO parameterTypeException(HttpMessageConversionException exception) {
        log.info("参数类型转换错误:{}", exception.getCause().getLocalizedMessage());
        return ResultVO.fail("类型转换错误");
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ResultVO handleBindException(BindException ex) {
        //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
        String message;
        FieldError fieldError = ex.getBindingResult().getFieldError();
        if(fieldError != null){
            message = fieldError.getDefaultMessage();
            log.info("必填校验异常:{}({})", message, fieldError.getField());
        }else{
            message = ex.getMessage();
            log.info("必填校验异常:{})", message);
        }
        return ResultVO.fail(message);
    }

}
